package com.hmkj.trade_push.job;

import com.alibaba.fastjson.JSON;
import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.core.api.ufx.call.TransactionCall;
import com.hmkj.core.api.ufx.model.res.LoginRes;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.po.commo.Commo;
import com.hmkj.core.po.investor.Investor;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.investor.InvestorService;
import com.hmkj.core.service.user.UserService;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 每日初始化资金账号登陆
 *
 * @author Vector
 * @create 2017-09-20 14:39
 */
@Slf4j
@Component
public class ReLoginJob {
    @Resource
    private InvestorService investorService;
    @Resource
    private UserService userService;
    @Resource
    private RedisService redisService;

    /**
     * 每日初始化资金账号登陆
     * 每日 06:56:00 执行
     */
//    @Scheduled(cron = "0 56 6 * * ?")
    public void relogin() throws Exception {
        List<Investor> list = investorService.select(new Investor(t -> {
            t.setDelFlag(GenericPo.DELFLAG.NORMAL.code);
            t.setStatus(Investor.STATUS.T1.code);
        }));
        if (CollectionUtils.isNotEmpty(list)) {
            for (Investor investor : list)
                try {
                    User user = userService.selectByPrimaryKey(investor.getUserId());
                    // 调用易盛接口进行登录，并获取资金账号
                    LoginRes res = TransactionCall.getInstance().accountLogin(getOpStation(user.getMobile()), investor.getAccountNo(), investor.getAccountPwd(), Commo.TYPE.T1.code);
                    log.info("易盛登录结果：" + JSON.toJSONString(res));
                    if (res == null || StrUtil.isBlank(res.getUserToken()))
                        throw new BussinessException("易盛登录失败，返回信息：{}", JSON.toJSONString(res));
                    redisService.put(CacheID.INVESTOR + investor.getAccountNo(), res.getUserToken(), 60 * 60 * 1);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("更新投资人易盛登录令牌失败，投资人ID：{}，错误消息：{}", investor.getId(), e.getMessage());
                }
        }
    }

    /**
     * 获取站点信息
     *
     * @param mobile
     * @return
     */
    private String getOpStation(String mobile) {
        return "MPN:" + mobile + ";" + "IP:47.93.207.165";
    }
}
